#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "util.h"
#include "Thread.h"
#include "log.h"
Thread::Thread(const ThreadFunc& func,const std::string& name):m_func(func),m_name(name){
    if(name.empty()){
        setDefaultName();
    }
}

void start_helper(std::vector<pid_t>& vec_tid,Thread& obj){
    pid_t tmp_id=getpid();
    {
        std::unique_lock<std::mutex> lock(obj.t_m_mtx);
        vec_tid.push_back(tmp_id);
        obj.t_m_cv.notify_all();
    }
    obj.m_func();
}

void Thread::start(){
    std::vector<pid_t> vec_tid;
    std::thread mythread(start_helper,std::ref(vec_tid),std::ref(*this));
    m_started=true;
    mythread.detach();
    std::unique_lock<std::mutex> lock(t_m_mtx);
    t_m_cv.wait(lock,[&]{
        return !vec_tid.empty();
    });
    if(vec_tid.empty()){
        record(Level::Error)<<"ipc error";
        exit(0);
    }
    m_tid=vec_tid[0];
}

int Thread::tid() const{
    if(!m_started){
        return -1;
    }
    return m_tid;
}
std::string Thread::name()const{
    return m_name;
}
//暂时用TIME, DATE有空格, 不象处理那么麻烦
void Thread::setDefaultName(){
    m_name=__TIME__;
}